package common

import (
	"fmt"
	"os"
	"path/filepath"
)

// findProjectRoot 递归查找包含指定文件的目录
func findProjectRoot(dir, markerFile string) (string, error) {
	for {
		if _, err := os.Stat(filepath.Join(dir, markerFile)); err == nil {
			return dir, nil
		}

		parentDir := filepath.Dir(dir)
		if parentDir == dir {
			return "", fmt.Errorf("could not find project root with marker file %s", markerFile)
		}
		dir = parentDir
	}
}

func ProjectDir() string {
	// 假设我们要通过 go.mod 文件来确定项目根目录
	markerFile := "go.mod"

	// 获取当前工作目录
	currentDir, err := os.Getwd()
	if err != nil {
		fmt.Println("Error getting current directory:", err)
		return ""
	}

	// 查找项目根目录
	projectRoot, err := findProjectRoot(currentDir, markerFile)
	if err != nil {
		fmt.Println("Error finding project root:", err)
		return ""
	}

	fmt.Println("Project Root Directory:", projectRoot)

	return projectRoot
}
